package com.example.demo;

import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.security.SecurityProperties.User;
import org.springframework.stereotype.Component;

/**
 * @author lizhien (zhien.li@nascent.cn)
 * @version 1.0.0
 * @date 2022/3/18 16:02
 * @description com.example.demo
 */

@Slf4j
@Component
@Aspect
public class UserAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(* com.example.demo.UserController.*(..))")
    public void user() {
        logger.info("切面===初始化。。。");
    }

    @Before("user()")
    public void beforeControllerMethod(JoinPoint joinPoint) {
        logger.info("切面===进入TimeAspect切面,执行之前");
    }

    @Around("user()")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        logger.info("切面===进入TimeAspect切面");
        Object[] args = pjp.getArgs();
        Arrays.asList(args).forEach(arg -> logger.info("切面===原方法参数：" + arg));
        long start = System.currentTimeMillis();
        Object obj = pjp.proceed();
        if (obj instanceof User) {
            User user = (User) obj;
            user.setPassword(user.getPassword() + "=000000000000000000000");
        }
        logger.info("切面===对象：" + obj);
        logger.info("切面===执行耗时：" + (System.currentTimeMillis() - start) + "ms");
        return obj;
    }

    @After("user()")
    public void afterControllerMethod(JoinPoint joinPoint) {
        logger.info("切面===进入TimeAspect切面,执行之后");
    }

    @AfterReturning(returning = "result", pointcut = "user()")
    public void doAfterReturnint(Object result) {
        logger.info("切面===方法返回值：" + result.toString());
    }
}
